//
//  HomeTableViewController.swift
//  微博天下

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController ,StatusCellDelegate {

    /// 微博数据的数据
    var statuses : [TSZHomeMircoblogModel]?{
        didSet{
            //刷新表格
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if !TSZUserAcountModel.userLogin {
            
            visitorView?.setupInfo(true, imageName: "visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        loadData()
        
        //MARK: 注册点击 图片的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectorPicture:", name:TSZMricoblogPritureActionNotification ,
            object: nil)
    }
    
    //实现StatusCellDelegate 的代理方法
    func statusCellDidClickURL(urlString: String) {
        //根据这个路径进行web页面的加载
        
        
        if let url = NSURL(string: urlString){
            let vc = TSZWebViewController()
            
            vc.url = url
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    
    //通知的实现方法
   @objc private func selectorPicture(notify: NSNotification){
    
    guard let urls = notify.userInfo![TSZMricoblogCellSelectPictureURLKey] as? [NSURL] else{
        print("url 不存在")
        return
    }
    guard let indexPath = notify.userInfo![TSZMricoblogCellSelectPictureIndexKey] as? NSIndexPath else{
        print("indexPath 不存在")
        return
    }
    
    guard let pictureIcon = notify.object as? TSZPictureView else{
        print("图像不存在")
        return
    }
    
    
//TODO: 记录属性
    pictureView = pictureIcon
    //设置转场动画的图像
    presentIconView.sd_setImageWithURL(urls[indexPath.item])
    
    //起始图片的索引
    currentIndex = indexPath
// 初始化控制器
    let photoVc = TSZPhotoBrowserCollection(urls: urls, index: indexPath.item)
    
    //实现自定义转场动画的协议
    photoVc.transitioningDelegate = self
    
    //指定转场动画的模式
    photoVc.modalPresentationStyle = UIModalPresentationStyle.Custom
    
    
//    modal到图片查看器的界
   presentViewController(photoVc, animated: true, completion: nil)

    }
    //记得注销通知
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /**
    准备表格
    */
    func prepareTableView() {
        //注册原型cell
        tableView.registerClass(TSZNomalCell.self, forCellReuseIdentifier: StatausCellIdentifier.NormalCell.rawValue)
        
        tableView.registerClass(TSZReprintCell.self, forCellReuseIdentifier: StatausCellIdentifier.ReprintCell.rawValue)
        // 设置表格的预估行高(方便表格提前计算预估行高，提高性能)
//        tableView.rowHeight = 200
        tableView.estimatedRowHeight = 300
        tableView.rowHeight  = UITableViewAutomaticDimension
        //MARK - 加载xib的试图
        refreshControl = TSZRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    //MARK - 上拉刷新的标记
    private var pullupResfreshFlag = false
    /**
    * 加载数据
    */
    func loadData(){
        //开始动画
        refreshControl?.beginRefreshing()
        
        //加载 20条数据
        var since_id = statuses?.first?.id ?? 0
        
        //上拉
        var max_id = 0
        
        print(pullupResfreshFlag)
        
        if pullupResfreshFlag {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        
        
        TSZHomeMircoblogModel.loadHomeMricoblog (since_id, max_id: max_id ){ (dataList, error) -> () in
            //关闭刷新控件 ，结束刷新
            self.refreshControl?.endRefreshing()
            //复位 ,可以在进行上拉刷新
            self.pullupResfreshFlag = false
            if error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                print(error)
                return
            }
            
            let count = dataList?.count ?? 0
            
            //下拉提示
            if since_id > 0 {
                self.showPullDoenTip(count)
            }

            if count == 0 {
                return
            }
            if since_id > 0 {
                self.statuses = dataList! + self.statuses!
            }else if max_id > 0 {
                self.statuses! += dataList!
                
            }else {
                self.statuses = dataList
            }
        }
    }
    
    //MARK 显示刷新的 条数
    private func showPullDoenTip(count: Int){
        
        if tipLabel.layer.animationForKey("position") != nil{
            print("动画正在执行中...")
            return
        }
        
        //定义一个标签
        tipLabel.text = (count == 0) ? "亲，没有新的微博啦" : "刷新到\(count)条微博"
        //标签的初始位置
       let rect = tipLabel.frame
//        let rect1 = CGRectMake(0, -88, 375, 44) 这样可以解决，但是 没有扩展性
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            //自动反转动画
            UIView.setAnimationRepeatAutoreverses(true)
            //移动label的位置
           
            self.tipLabel.frame = CGRectOffset(rect, 0, 3*rect.height)
           
            }) { (_) -> Void in
                 print(rect)
                
                //将标签复位
                self.tipLabel.frame = rect
                //移除的话只能刷新一次？
//                self.tipLabel.removeFromSuperview()
        }
    }
    
//MARK - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //获取微博类型
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatausCellIdentifier.cellId(status), forIndexPath: indexPath)as! TSZStatusCell
        
            if indexPath.row == statuses!.count - 1 {
            //设置上拉刷新标记
            pullupResfreshFlag = true
            loadData()
        }
        
        //设置数据
        cell.statusDelegate = self
        cell.data = statuses![indexPath.row]
        return cell
    }
   //MARK - 重写行高的方法
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let  status = statuses![indexPath.row]
        if let h = status.rowHeight{
            return h
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatausCellIdentifier.cellId(status)) as! TSZStatusCell
        status.rowHeight = cell.rowHight(status)
        return status.rowHeight!
    }
    
//隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    //懒加载  提示的view
    
    private lazy var tipLabel: UILabel = {
        let  h: CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width: self.view.bounds.width, height: h))
        label.backgroundColor = UIColor.orangeColor()
        
        label.textColor = UIColor.whiteColor()
        
        label.textAlignment = NSTextAlignment.Center
        
        //加载navBar
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
        }()
    
    /**
    * 是否是Modal展示的标记
    */
    private var isPresented = false
    
    // 动画转场过程中的图像视图
    private lazy var presentIconView: UIImageView = {
            let iv = UIImageView()
        
            //图像的剪裁方式
            iv.contentMode = UIViewContentMode.ScaleAspectFill
            iv.clipsToBounds = true
        return iv
        }()
    //转场动画选中的图片
    private var pictureView: TSZPictureView?
    //转场动画的图片索引
    private var currentIndex: NSIndexPath?
    
    
}

//MARK: 自定义转场动画协议
/**
* 自定义转场动画
*/

extension HomeTableViewController: UIViewControllerTransitioningDelegate{
    //实现转场动画 都要遵守UIViewControllerTransitioningDelegate协议
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        //可是实现转场
        isPresented = true
        return self
    }
    
    //返回提供解除转场动画
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}
//MARK: 自定义转场动画
extension HomeTableViewController: UIViewControllerAnimatedTransitioning{
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 1.0
    }
    
    // 自定义转场动画 － 只要实现了此方法，就需要自己来动画代码
    /**
    transitionContext 提供了转场动画需要的元素
    
    completeTransition(true) 动画结束后必须调用的
    containerView() 容器视图
    
    viewForKey      获取到转场的视图
    */
    func  animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
//        
//        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        
        //MARK:  查看一下是那个页面跳到那个页面
//        print(fromVC)
//        print(toVC)
        
        //modal 展现视图
//        if isPresented {
//            //展现动画
//            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
//          
//            //将目标试图添加到容器试图shang
//            transitionContext.containerView()?.addSubview(toView)
//              toView.alpha = 0
//            //动画效果
//            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//                toView.alpha = 1.0
//                transitionContext.completeTransition(true)
//            })
//            
//        }else {
//            let fromVC  = transitionContext.viewForKey(UITransitionContextFromViewControllerKey)
//            
//            //MARK: fromVC的动画
//            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//                    fromVC?.alpha = 0.0
//                
//                }, completion: { (_) -> Void in
//                fromVC?.removeFromSuperview()
//                transitionContext.completeTransition(true)
//                    
//                    
//            })
//        }
        if isPresented {
            //转场后后显示的view
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            //将动画的图像视图添加到目标视图中
            transitionContext.containerView()?.addSubview(toView)
            
            //指定图像的起始的位置
            let fromRect = pictureView!.cellScreenFrame(currentIndex!)
            //显示的位置
            let toRect = pictureView!.cellFullScreenFrame(currentIndex!)
            
            //设置起始位置
            presentIconView.frame = fromRect
            
            //实现动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                //动画运动到目标的位置
                self.presentIconView.frame = toRect
                
                }, completion: { (_) -> Void in
                    //删除背景图像视图
//                    self.presentIconView.removeFromSuperview()
                    //添加目标视图
                    transitionContext.containerView()?.addSubview(toView)
                    //下列这句话一定要执行
                    transitionContext.completeTransition(true)
            })
            return
        }
        
        //MARK: 解除转场
        //照片查看器的控制器
        let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! TSZPhotoBrowserCollection
        
        //从控制器获取当前的图片的索引
        let indexPath = fromVc.currentImageIndex()
        
        //获得微博上cell对应的位置
        let rect = pictureView!.cellScreenFrame(indexPath)
        
        //图片试图
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        //获取当前的图像视图
        let iv = fromVc.currentImageView()
        //获取当前的图像视图的位置
        iv.center = fromView.center
        
        //累加父视图的形变
        let scale = fromView.transform.a
        
        iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
        //将当前的图像视图添加到容器视图
        transitionContext.containerView()?.addSubview(iv)
        
        //将父控件佛纳甘视图容器移除
        fromView.removeFromSuperview()
        
        //动画效果
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            //修改目标位置
            iv.frame = rect
            
            }) { (_) -> Void in
                iv.removeFromSuperview()
                //解除转场动画
                transitionContext.completeTransition(true)
        }
    }
}


